Grokking Scalable Systems for Interviews
Rate this course
Ask Author
Contribute
Back to course home

4% completed

Vote For New Content
Introduction
Course Overview
Who This Course Is for
Caching
What Is Negative Caching and When Should You Cache 404 or Empty Results?
What Is the Difference Between Soft TTL and Hard TTL, and Why Does It Matter?
How Can a Bloom Filter Reduce Cache or Database Load?
What Is Distributed Locking for Cache Rebuilds, and How Does It Prevent Cache Stampedes?
Load Balancing
What Are Sticky Sessions (Session Affinity) and When Should I Avoid Them?
What Is the Difference between Liveness Checks and Readiness Checks in Load Balancers?
What is Global Server Load Balancing (GSLB) and How GeoDNS and Anycast Work?
API Basics
What are the Main API Pagination Strategies (offset, cursor, keyset), and When Should I Use Each?
What are HTTP Conditional Requests (ETag, If‑None‑Match, Last‑Modified) and How They Reduce Load?
What Is the Difference between Rate Limiting and Throttling and Quotas?
What Are Idempotency Keys and How to Implement Them Safely for Payments
Databases
What are SQL Isolation Levels (Read Committed, Repeatable Read, Serializable), and What Anomalies Do They Prevent?
What Is a Write‑Ahead Log (WAL), and How Does It Ensure Durability?
What Is the Difference Between Synchronous and Asynchronous Replication, and When Should I Use Read Replicas?
What Is MVCC (Multi‑Version Concurrency Control), and How Does It Enable Concurrent Reads and Writes?
What Are Safe Patterns for Online Schema Changes vs. Offline Migrations?
Scalability
What is Little’s Law and How to Use It for Quick Capacity Estimates in System Design
How Can I do Back-of-the-Envelope Sizing for QPS, Bandwidth, Storage, and Peak vs. Average Load?
What are Cold Starts and Warm Starts, and Why Do They Matter for Performance?
Sharding and Partitioning
How Do I Choose a Good Shard Key and Avoid Hotspots (Bucketing and Key Randomization)?
What Are Range Sharding, Directory‑Based Sharding, and Geo‑Sharding, and What Are the Common Use Cases?
What Is the Difference Between Rendezvous Hashing and Consistent Hashing, and When Should I Use Each?
Messaging and Streaming
What Do At‑most‑once, At‑least‑once, And Exactly‑once Delivery Semantics Mean?
What Are Idempotent Producers And Consumers, And How Do De‑duplication Keys Work?
What Is Message Ordering, How Do Partition Keys Affect It, And When Can Ordering Break?
What Are Windowing And Watermarking In Streaming Systems, In Simple Terms?
Consistency and Replication
What Is Quorum (N, R, W), And Why Does R + W > N Give Strongly Consistent Reads?
What Are Common Conflict Resolution Strategies (Last‑write‑wins, Vector Clocks, Logical Clocks)?
What Are Read Repair, Hinted Handoff, And Anti‑entropy (Merkle Trees) In Eventually Consistent Systems?
Observability
What Is The Difference Between SLI, SLO, And SLA, And Can You Give Simple Examples?
What Is Opentelemetry, And How Do Traces, Spans, Metrics, And Logs Fit Together?
What Is An Error Budget, And How Should It Guide Release Decisions?
Security
What Are The Trade‑offs Between Server‑stored Sessions And JWTs for Authentication?
What Is The Difference Between TLS And MTLS, And When Is MTLS Appropriate For Service‑to‑service Auth?
What Is Secrets Management, And How Do Environment Variables, KMS, And Vault Compare?
What Is A Replay Attack, And How Is It Different from Idempotency Issues?
Networking
What Are The Differences Between TCP, UDP, And QUIC, And When Should I Use Each?
What Is The Difference Between A Forward Proxy, A Reverse Proxy, And NAT?
What Changed From HTTP/1.1 To HTTP/2 To HTTP/3, And What Are Head‑of‑line Blocking And Multiplexing?
Storage
What Is the Difference Between Content‑Addressable Storage and Location‑Based Addressing?
What Are Checksums and Etags, and How Do MD5/SHA Compare to CRC for Integrity?
What Are Hot, Warm, Cold, and Archive Storage Tiers, and When Should I Use Each?
Design Patterns
What Is the Outbox Pattern, and How Does Change Data Capture (CDC) Work at a High Level?
What Is CQRS (Command Query Responsibility Segregation), and When Should I Consider It?
What Are the Differences Between a Circuit Breaker, Retry With Backoff, and Rate Limiting?
Reliability and Operations
What Are RPO and RTO, and How Do They Differ in Disaster Recovery Planning?
What Is the Difference Between Active‑Active and Active‑Passive Architectures?
What Is Graceful Degradation, and How Do Feature Flags Help Availability?
Time and IDs
What Are the Differences Between UUID, ULID, KSUID, and Snowflake IDs, and How Do I Choose?
How Do Snowflake‑Style IDs Work (Timestamp, Worker, Sequence), and What Problems Do They Solve?
What Is the Difference Between Wall‑Clock Time and Monotonic Time, and Why Is Clock Skew Hard?
Final Words
Key Takeaways
What To Learn Next
How Do Snowflake‑Style IDs Work (Timestamp, Worker, Sequence), and What Problems Do They Solve?

Snowflake IDs are distributed, globally unique 64-bit identifiers that combine a timestamp, a machine (worker) ID, and a sequence counter to produce roughly time-ordered IDs.

In other words, each Snowflake ID embeds when (timestamp), where (which server or process), and which (sequence number) it was created, making it unique without a central coordinator.

This format was created by Twitter (X) for tweet IDs and is now used by systems like Discord and Instagram, solving the problem of generating unique identifiers at scale.

In practice, Snowflake IDs let each server or node in a distributed system generate its own IDs without conflict.

Because the timestamp portion is first, Snowflake IDs sort in time order and even allow you to extract the creation time from the ID. This solves a common challenge in distributed systems: how to generate unique, sortable IDs across many machines without a single bottleneck.

Structure: Timestamp, Worker, Sequence

Each Snowflake ID is a 64-bit number partitioned into fields.

A typical layout (Twitter’s original Snowflake) looks like this:

Snowflake ID Structure
Snowflake ID Structure

Snowflake ID Structure

Each Snowflake ID is a 64-bit integer split into a high-resolution timestamp, a worker (machine or node) ID, and a sequence number, as shown above.

In one common scheme, the first bit is 0 (sign bit), the next 41 bits hold the millisecond timestamp (since a custom epoch), the next 10 bits encode the worker or machine ID, and the last 12 bits are a sequence counter.

These fields work together as follows:

  • Timestamp (e.g. 41 bits): Records the creation time in milliseconds (usually since a custom epoch). This makes IDs time-ordered and allows systems to sort or filter items by when they were created. For example, Twitter’s epoch is Nov 04 2010, so the timestamp bits show milliseconds since then. Because the timestamp is the highest-order part of the ID, newer IDs are always larger than older ones.

  • Worker/Node ID (e.g. 10 bits): Identifies which machine or process generated the ID. In a cluster, each server has a unique worker (or machine) number. This field prevents different servers from creating the same ID. (Some Snowflake variants split these 10 bits into a 5-bit datacenter ID + 5-bit machine ID, as noted in Twitter’s design.)

  • Sequence (e.g. 12 bits): A counter that increments for each ID generated on the same worker within the same millisecond. If a node generates multiple IDs in one millisecond, the sequence bits step through 0, 1, 2, … up to their max (4095 with 12 bits) before moving to the next millisecond. This ensures that even rapid, concurrent ID requests on a single machine remain unique.

Because of this structure, Snowflake IDs are ordered by time and unique across machines.

One can decode a Snowflake ID to get its timestamp and worker ID, and the IDs naturally increment over time on each node.

Advantages and Problems Solved

Snowflake IDs solve several key problems in distributed systems by design:

  • Global Uniqueness (no collisions): By including a unique worker ID and sequence, two different servers or processes will never generate the same ID even if they act simultaneously. Each node’s ID space is disjoint, so there’s no need for a central ID service or database lock. This eliminates duplicate-ID bugs in distributed environments.

  • Time-Ordering: Since the timestamp is the most significant part, Snowflake IDs are approximately sorted by creation time. You can fetch “recent” records by looking at ID ranges. This solves the problem of needing a separate timestamp or sort key for chronological queries.

  • High Throughput: A Snowflake setup can handle very high ID generation rates. For example, with 12 sequence bits, one server can make up to 4,096 unique IDs per millisecond (over 4 million IDs/sec). The scheme automatically wraps to the next millisecond if the counter overflows, so systems rarely exhaust their ID rate.

  • No Central Bottleneck: Traditional auto-increment IDs or database sequences can become contention points under heavy load. Snowflake is stateless: each server generates IDs independently. This solves scalability issues by removing any single point of coordination.

  • Efficiency: A Snowflake ID is just a 64-bit integer, smaller than a 128-bit UUID. This saves storage and speeds up database indexing and joins.

In summary, Snowflake-style IDs provide a distributed, collision-free, and sortable way to assign identifiers at scale. They remove the need for a central ID issuer and ensure consistency even in large clusters.

Use Cases and Examples

Snowflake IDs are widely used where massive, distributed ID generation is needed. For example:

  1. Social Media Posts: Twitter originally used Snowflake IDs for tweets. Each tweet’s ID encodes its post time. If two tweets occur at nearly the same moment, their sequence numbers differ so the IDs stay unique. This lets Twitter quickly order tweets by ID and derive timestamps from them. Discord and Instagram similarly use Snowflake-style IDs for messages and posts, so engineers can sort or shard data by ID.

  2. Messaging and Events: In a chat app, each message might get a Snowflake ID. If two messages are sent at the same millisecond on different servers, the differing worker IDs keep the Snowflake IDs distinct. The sequence bits ensure that if one server sends several messages rapidly, each still has a unique ID.

  3. Distributed Databases: When sharding databases, Snowflake IDs can serve as primary keys. Because IDs indicate the shard (via worker bits) and time, records are naturally grouped by time and location. Queries for recent records or time ranges become simple range scans on the key.

  4. Logging and Data Pipelines: Systems that ingest events (logs, analytics, IoT readings) often need unique event IDs without coordination. Snowflake IDs let each sensor or process stamp its data with a globally unique ID that also tells when it was logged, aiding event ordering and deduplication.

Example Scenario

Imagine an e-commerce site with servers around the world. When customers place orders, each server generates a Snowflake ID for the order.

Because each server has a unique worker ID, no two orders will ever collide, even without talking to each other.

The order IDs are roughly increasing with time, so later orders have bigger IDs.

The business can sort orders by Snowflake ID to see recent ones first, and even decode the timestamp to see when each order was placed.

Compared to alternatives, Snowflake IDs strike a balance of features. Unlike random UUIDs, Snowflakes are time-ordered and compact.

Unlike a simple auto-increment sequence, they avoid a single point of failure or lock.

In short, Snowflake IDs solve the challenge of generating unique, meaningful IDs in large distributed systems.

What Are the Differences Between UUID, ULID, KSUID, and Snowflake IDs, and How Do I Choose?
What Is the Difference Between Wall‑Clock Time and Monotonic Time, and Why Is Clock Skew Hard?
Mark as Completed

On this page

Structure: Timestamp, Worker, Sequence

Snowflake ID Structure

Advantages and Problems Solved

Use Cases and Examples

Example Scenario